package GDoc::Job::Fetch::US::Judi::USCA::USCA05;

use Moose;
use GDoc::Job;
use File::Temp;
use HTML::TableContentParser;
use Data::Dumper;

extends 'GDoc::Job::Fetch';



sub setup { 
    my $self = shift;

    $self->_baseurl( 'http://www.ca5.uscourts.gov/Opinions.aspx' );
}


sub run { 
    my $self = shift;
    
    if ( $self->data->{link} ) { 
        $self->_fetch_pdf;
    } else { 
        my $mech = $self->_mech;
        $mech->get( $self->_baseurl );

        foreach my $year( 2007 .. 2007 ) { 
            foreach my $ten( 3 .. 3 ) { 
                my $numpart = substr( $year, 2, 2 );
                $numpart .= '-' . $ten;

                $self->logger->info( "num = $numpart" );
                $mech->submit_form( fields => { txtDocketNumber => $numpart,
                                                btnSearch       => 'Search', 
                                              } );

                my $parser = HTML::TableContentParser->new;
                my $tbls = $parser->parse( $mech->response->content );

                my $pubtbl    = $tbls->[7];
                my $unpubtbl  = $tbls->[8];

                $self->logger->info( Dumper( $pubtbl, $unpubtbl ) );

                last;
            }
        }
    }
}


sub _fetch_pdf { 
    my $self = shift;
    my %data = %{ $self->data };

    $data{link} =~ m{(?<year>\d{2})-(?<num>\d{1,5})};
    my ( $year, $num ) = @+{ 'year', 'num' };

    unless( $year and $num ) { 
        $self->logger->error( "Can't parse year and docket number from $data{link}" );
        return;
    }

    my $ident = sprintf( 'USCA05-OP-%04d-%05d', $data{year}, $num );
    my $filename = $ident . '.pdf';
    my $key = 'us/judi/usca/usca05/' . $filename;

    if ( $self->_check_key( $key ) ) { 
        $self->logger->info( "Already have $data{link}, skipping" );
        return;
    }

    # get case metadata
    my $meta = $self->_get_metadata( $year, $num );

    $self->logger->info( "Storing $data{link} --> $key" );
}




1;
